﻿using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sino.CapacityCloud.Services
{

    public abstract class ConfigurableServiceBase
    {

        private IConfigurationBuilder _configurationBuilder;

        protected IConfigurationBuilder ConfigurationBuilder
        {
            get
            {
                return this._configurationBuilder;
            }
            set
            {
                if (this._configurationBuilder != value)
                {
                    this._configurationBuilder = value;
                    this.Configuration = this._configurationBuilder.Build();
                }
            }
        }

        public IConfiguration Configuration { get; protected set; }

        public ConfigurableServiceBase(IConfigurationBuilder builder)
        {
            this.ConfigurationBuilder = builder;
        }

        public ConfigurableServiceBase(IHostingEnvironment env, string configurationFileName = "appsettings")
        {
            this._configurationBuilder = new ConfigurationBuilder()
               .AddJsonFile($"{configurationFileName}.json")
               .AddJsonFile($"{configurationFileName}.{env.EnvironmentName}.json", optional: true)
               .AddEnvironmentVariables();

            this.Configuration = this._configurationBuilder.Build();
        }

        public ConfigurableServiceBase(IHostingEnvironment env, string section, string configurationFileName = "appsettings")
        {
            this._configurationBuilder = new ConfigurationBuilder()
               .AddJsonFile($"{configurationFileName}.json")
               .AddJsonFile($"{configurationFileName}.{env.EnvironmentName}.json", optional: true)
               .AddEnvironmentVariables();

            this.Configuration = this._configurationBuilder.Build().GetSection(section);
        }

    }

}
